const Shop = require('../models/shop.model');
const Product = require('../models/product.model');
const User = require('../models/user.model');

/**
 * 获取所有店铺
 * GET /api/shops
 */
exports.getAllShops = async (req, res, next) => {
  try {
    const {
      keyword = '',
      category = '',
      type = '',
      status = 'active',
      page = 1,
      limit = 10,
      sort = '-createdAt'
    } = req.query;

    // 构建查询条件
    const query = { status };

    // 关键词搜索
    if (keyword) {
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { description: { $regex: keyword, $options: 'i' } },
        { tags: { $in: [new RegExp(keyword, 'i')] } }
      ];
    }

    // 分类过滤
    if (category) {
      query.categories = { $in: [category] };
    }

    // 店铺类型过滤
    if (type) {
      query.type = type;
    }

    // 分页参数
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const skip = (pageNum - 1) * limitNum;

    // 执行查询
    const shops = await Shop.find(query)
      .populate('owner', 'name avatar')
      .sort(sort)
      .skip(skip)
      .limit(limitNum);

    // 获取总数
    const total = await Shop.countDocuments(query);

    res.json({
      success: true,
      data: {
        shops,
        page: pageNum,
        pages: Math.ceil(total / limitNum),
        total
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取店铺详情
 * GET /api/shops/:id
 */
exports.getShopById = async (req, res, next) => {
  try {
    const shop = await Shop.findById(req.params.id)
      .populate('owner', 'name avatar email phone')
      .populate('followers', 'name avatar');

    if (!shop) {
      return res.status(404).json({ message: '店铺不存在' });
    }

    res.json({
      success: true,
      data: shop
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 创建店铺
 * POST /api/shops
 */
exports.createShop = async (req, res, next) => {
  try {
    const {
      name,
      description,
      logo,
      banner,
      categories,
      contact,
      announcement,
      tags,
      shipping,
      afterSales
    } = req.body;

    // 检查用户是否已有店铺
    const existingShop = await Shop.findOne({ owner: req.user.id });
    if (existingShop) {
      return res.status(400).json({ message: '您已经拥有一个店铺' });
    }

    // 创建店铺
    const shop = await Shop.create({
      name,
      description,
      logo,
      banner,
      owner: req.user.id,
      categories,
      contact,
      announcement,
      tags,
      shipping,
      afterSales
    });

    // 填充店主信息
    await shop.populate('owner', 'name avatar email');

    res.status(201).json({
      success: true,
      data: shop
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 更新店铺信息
 * PUT /api/shops/:id
 */
exports.updateShop = async (req, res, next) => {
  try {
    const shop = await Shop.findById(req.params.id);

    if (!shop) {
      return res.status(404).json({ message: '店铺不存在' });
    }

    // 检查权限：只有店主或管理员可以更新
    if (shop.owner.toString() !== req.user.id && !req.user.isAdmin) {
      return res.status(403).json({ message: '没有权限更新此店铺' });
    }

    // 更新店铺信息
    const updatedShop = await Shop.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true, runValidators: true }
    ).populate('owner', 'name avatar email');

    res.json({
      success: true,
      data: updatedShop
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 删除店铺
 * DELETE /api/shops/:id
 */
exports.deleteShop = async (req, res, next) => {
  try {
    const shop = await Shop.findById(req.params.id);

    if (!shop) {
      return res.status(404).json({ message: '店铺不存在' });
    }

    // 检查权限：只有店主或管理员可以删除
    if (shop.owner.toString() !== req.user.id && !req.user.isAdmin) {
      return res.status(403).json({ message: '没有权限删除此店铺' });
    }

    // 检查是否有商品
    const productCount = await Product.countDocuments({ shop: req.params.id });
    if (productCount > 0) {
      return res.status(400).json({ message: '店铺内还有商品，无法删除' });
    }

    await Shop.findByIdAndDelete(req.params.id);

    res.json({
      success: true,
      message: '店铺已删除'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取店铺商品
 * GET /api/shops/:id/products
 */
exports.getShopProducts = async (req, res, next) => {
  try {
    const {
      category = '',
      page = 1,
      limit = 10,
      sort = '-createdAt'
    } = req.query;

    // 构建查询条件
    const query = { shop: req.params.id };

    if (category) {
      query.category = category;
    }

    // 分页参数
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);
    const skip = (pageNum - 1) * limitNum;

    // 执行查询
    const products = await Product.find(query)
      .populate('shop', 'name logo rating')
      .sort(sort)
      .skip(skip)
      .limit(limitNum);

    // 获取总数
    const total = await Product.countDocuments(query);

    res.json({
      success: true,
      data: {
        products,
        page: pageNum,
        pages: Math.ceil(total / limitNum),
        total
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 关注/取消关注店铺
 * POST /api/shops/:id/follow
 */
exports.toggleFollowShop = async (req, res, next) => {
  try {
    const shop = await Shop.findById(req.params.id);

    if (!shop) {
      return res.status(404).json({ message: '店铺不存在' });
    }

    const userId = req.user.id;
    const isFollowing = shop.followers.includes(userId);

    if (isFollowing) {
      // 取消关注
      shop.followers = shop.followers.filter(id => id.toString() !== userId);
      shop.stats.followers = Math.max(0, shop.stats.followers - 1);
    } else {
      // 关注
      shop.followers.push(userId);
      shop.stats.followers += 1;
    }

    await shop.save();

    res.json({
      success: true,
      data: {
        isFollowing: !isFollowing,
        followersCount: shop.stats.followers
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取店铺统计信息
 * GET /api/shops/:id/stats
 */
exports.getShopStats = async (req, res, next) => {
  try {
    const shop = await Shop.findById(req.params.id);

    if (!shop) {
      return res.status(404).json({ message: '店铺不存在' });
    }

    // 检查权限：只有店主或管理员可以查看详细统计
    if (shop.owner.toString() !== req.user.id && !req.user.isAdmin) {
      return res.status(403).json({ message: '没有权限查看店铺统计' });
    }

    // 更新统计信息
    await shop.updateStats();

    res.json({
      success: true,
      data: shop.stats
    });
  } catch (error) {
    next(error);
  }
};
